<?php
namespace application\common\model;
use think\Db;
/**
 * 文章类形内容存储器
 */
class Article
{
	public $code;
	public $message;
	private $currentTalbe;	//当前表格信息
	private $tableBase   = 'article_base';
	private $tableDetail = 'article_detail';
	private $tableReply  = 'article_reply';
	/**
	 * 获取当前数据表格 
	 */
	public function __construct()
	{
	}
	/**
	 * 检测空参数
	 * @param array $params	参数列表
	 * @param array $data  	内容
	 */
	private function chkEmptyParam($params, $data)
	{
		if (!$data) return false;
		if (!is_array($params)) $params = explode(',', $params);//非数组则转换
		foreach ($params as $val) {
			if (!isset($data[$val]) || empty($data[$val])) return $val;
		}
		return false;
	}
	/**
	 * 标题是否唯一，仅仅检测当前数据表格
	 * @param string $title  标题
	 * @return bool 唯一true, 否false
	 */
	public function chkTitleUnique($title)
	{
		//base表格名称
		$tableBase = $this->tableBase . $this->currentTalbe['index_id'];
		//标题是否唯一，不唯一直接返回成功
		$titleInfo = Db::table($tableBase)
						->field(['aid'])
						->where(['title' => $title])
						->find();
		if ($titleInfo) {
			return false;
		} else {
			return true;
		}
	}
	/**
	 * 获取内容详情
	 * @param string $content  
	 */
	private function getSummary($content) 
	{
		return mb_substr(preg_replace('/<[^>]*?>/is', '', $content), 0, 200);
	}
	/**
	 * 保存数据操作
	 * @param array $data  
	 * @return bool || int $aid
	 */
	private function saveData($data) 
	{
		$nowTime = time();
		//保存基本信息
		$base = [
			'title' 		=> (string)$data['title'],
			'catid' 		=> (int)$data['catid'],
			'headpic' 		=> !empty($data['headpic'])?$data['headpic']:'',
			'writer'		=> !empty($data['writer'])?$data['writer']:'',
			'source'		=> !empty($data['source'])?$data['source']:'',
			'source_url'	=> !empty($data['source_url'])?$data['source_url']:'',
			'reply_count'	=> !empty($data['reply_count'])?$data['reply_count']:(is_array($data['reply'])?count($data['reply']):0),
			'click_count'	=> !empty($data['click_count'])?$data['click_count']:0,
			'pub_time'		=> !empty($data['pub_time'])?$data['pub_time']:0,
			'create_time' 	=> $nowTime
		];
		//base表格名称
		$tableBase = $this->tableBase;
		//标题是否唯一，不唯一直接返回成功
		$titleInfo = Db::table($tableBase)
						->field(['aid'])
						->where(['title'=>$base['title']])
						->find();
		if ($titleInfo) {
			return $titleInfo['aid'];
		}
		//保存内容基本信息
		Db::table($tableBase)->insert($base);
		$aid = Db::table($tableBase)->getLastInsID();	//取得aid
		if (!$aid) {
			$this->code    = '1011';
			$this->message = '系统出错，内容保存失败';
			return false;
		}
		//内容详情
		$content = [
			'aid' 	  => $aid,
			'content' => $data['content'],
			'summary' => !empty($data['summary'])?$data['summary']:$this->getSummary($data['content']),
			'imglist' => !empty($data['imglist'])?json_encode($data['imglist'], JSON_UNESCAPED_UNICODE):'',
			'taglist' => !empty($data['taglist'])?$data['taglist']:''
		];
		$tableDetail = $this->tableDetail;
		$insRes = Db::table($tableDetail)->insert($content);
		if(!$insRes) Db::table($tableBase)->where('aid', $aid)->update(['status' => '4']); //详情保存失败，设置该信息无效
		//回复评论
		if (isset($data['reply']) && is_array($data['reply'])) {
			$replyArr = [];
			foreach ($data['reply'] as $val) {
				if (empty($val['reply_cnt'])) continue;
				$replyArr[] = [
						'aid' 		=> $aid,
						'out_id'	=> !empty($val['out_id'])?$val['out_id']:0,
						'pid'		=> !empty($val['pid'])?$val['pid']:0,
						'replier'	=> !empty($val['replier'])?$val['replier']:'',
						'reply_cnt' => $val['reply_cnt'],
						'reply_time'=> !empty($val['reply_time'])?$val['reply_time']:0
				];
			}
			if ($replyArr) {
				$tableReply = $this->tableReply;
				Db::table($tableReply)->insertAll($replyArr);
			}
		}
		return $aid;
	}	
	/**
	 * 保存内容
	 * @param array $data
	 */
	public function saveArticle($data)
	{
		if (!$data) {
			$this->code    = '520';
			$this->message = sprintf('保存失败，字段内容为空');
			return false;
		}
		//保存数据,获取aid
		$aid = $this->saveData($data);
		if (!$aid) return false;
		//返回数据插入获取的aid
		return $aid;
	}
}